<template>
  <div class="editor-container" style="display: flex; height: 600px; border: 1px solid #ccc;">
    <!-- 左侧按钮 -->
    <div class="button-panel" style="width: 200px; padding: 15px; border-right: 1px solid #ddd; background: #f8f9fa;">
      <h4>可拖拽按钮</h4>
      <div
        v-for="(btn, index) in dragButtons"
        :key="index"
        draggable="true"
        @dragstart="onDragStart($event, btn)"
        style="
          display: inline-block;
          margin: 5px;
          padding: 8px 12px;
          background: #007bff;
          color: white;
          border: none;
          border-radius: 4px;
          cursor: move;
          user-select: none;
        "
      >
        {{ btn.label }}
      </div>
    </div>

    <!-- 富文本编辑器 -->
    <div class="editor-wrapper" style="flex: 1; padding: 10px;">
      <QuillEditor
        ref="quillEditor"
        theme="snow"
        :options="editorOptions"
        @ready="onEditorReady"
      />
    </div>

    <!-- 弹窗 -->
    <teleport to="body">
      <div v-if="showModal" class="modal" style="
        position: fixed; top: 0; left: 0; width: 100%; height: 100%;
        background: rgba(0,0,0,0.5); display: flex; align-items: center; justify-content: center;
        z-index: 9999;
      ">
        <div style="background: white; padding: 20px; border-radius: 8px; width: 300px;">
          <h5>选择替换内容</h5>
          <ul style="list-style: none; padding: 0;">
            <li
              v-for="(item, i) in replaceOptions"
              :key="i"
              @click="selectReplacement(item)"
              style="padding: 10px; cursor: pointer; border-bottom: 1px solid #eee;"
            >
              {{ item.label }}
            </li>
          </ul>
          <button @click="showModal = false" style="margin-top: 10px;">取消</button>
        </div>
      </div>
    </teleport>
  </div>
</template>

<script setup lang="ts">
import { ref, onMounted } from 'vue'
import { QuillEditor } from '@vueup/vue-quill'
import '@vueup/vue-quill/dist/vue-quill.snow.css'
import Quill from 'quill'

// === 数据定义 ===
const CUSTOM_BUTTON_BLOT = 'customButtonBlot'

const dragButtons = [
  { label: '按钮1', value: 'btn1' },
  { label: '按钮2', value: 'btn2' },
  { label: '按钮3', value: 'btn3' },
]

const replaceOptions = [
  { label: '替换为：红色文字A', value: 'redTextA' },
  { label: '替换为：红色文字B', value: 'redTextB' },
]

const showModal = ref(false)
let currentButtonData: { value: string; index: number } | null = null
const quillEditor = ref<any>(null)
let quillInstance: any = null

const editorOptions = {
  modules: { toolbar: [['bold'], ['link'], ['clean']] },
  placeholder: '拖拽按钮到这里...',
}

// === 拖拽开始 ===
const onDragStart = (e: DragEvent, btn: { label: string; value: string }) => {
  e.dataTransfer?.setData('text/plain', JSON.stringify(btn)) // 序列化整个对象
  e.dataTransfer!.effectAllowed = 'copy'
}

// === 编辑器就绪 ===
const onEditorReady = async (editor: any) => {
  // 延迟确保 Quill 完全初始化
  await new Promise(resolve => setTimeout(resolve, 50))
  
  quillInstance = editor.getQuill()

  // 动态创建 style 标签注入到编辑器内部（关键！）
  const style = document.createElement('style')
  style.textContent = `
    .ql-custom-button-inline {
      display: inline-block !important;
      padding: 2px 6px !important;
      margin: 0 4px !important;
      background-color: #007bff !important;
      color: white !important;
      border: none !important;
      border-radius: 4px !important;
      cursor: pointer !important;
      font-size: 13px !important;
      line-height: 1 !important;
      text-align: center !important;
      user-select: none !important;
    }
  `
  quillInstance.root.appendChild(style) // 将样式直接插入编辑器内容区

  // 导入 Inline
  const Inline = Quill.import('blots/inline')

  // 自定义 Blot 类
  class CustomButtonBlot extends Inline {
    static create(dataStr: string) {
      const data = JSON.parse(dataStr)
      const node = super.create()
      node.innerHTML = data.label
      node.setAttribute('data-value', data.value)
      node.setAttribute('data-blot', CUSTOM_BUTTON_BLOT)
      node.className = 'ql-custom-button-inline' // 使用内联样式类
      node.contentEditable = 'false'
      return node
    }

    static value(node: HTMLElement) {
      return {
        label: node.innerText,
        value: node.getAttribute('data-value'),
      }
    }

    attach() {
      super.attach()
      this.listener = this.handleClick.bind(this)
      this.domNode.addEventListener('click', this.listener)
    }

    detach() {
      if (this.listener) {
        this.domNode.removeEventListener('click', this.listener)
      }
      super.detach()
    }

    listener: (() => void) | null = null

    handleClick() {
      console.log('按钮被点击') // 调试
      const value = this.domNode.getAttribute('data-value')
      const index = quillInstance.getIndex(this)
      currentButtonData = { value: value!, index }
      showModal.value = true
    }
  }

  CustomButtonBlot.blotName = CUSTOM_BUTTON_BLOT
  CustomButtonBlot.tagName = 'SPAN'

  // 注册前先注销（防止重复）
  try {
    Quill.unregister(`blots/${CUSTOM_BUTTON_BLOT}`)
  } catch (e) {}

  Quill.register(CustomButtonBlot, true)

  // ==== 拖放支持 ====
  quillInstance.root.addEventListener('dragover', (e: DragEvent) => {
    e.preventDefault()
    e.dataTransfer!.dropEffect = 'copy'
  })

  quillInstance.root.addEventListener('drop', (e: DragEvent) => {
    e.preventDefault()
    const data = e.dataTransfer?.getData('text/plain')
    if (!data) return

    try {
      const btn = JSON.parse(data)
      const range = quillInstance.getSelection()
      const index = range ? range.index : 0

      quillInstance.insertEmbed(index, CUSTOM_BUTTON_BLOT, JSON.stringify(btn))
      quillInstance.setSelection(index + 1)
    } catch (err) {
      console.error('解析拖拽数据失败', err)
    }
  })
}

// === 替换逻辑 ===
const selectReplacement = (item: { label: string; value: string }) => {
  if (currentButtonData && quillInstance) {
    const { index } = currentButtonData
    quillInstance.deleteText(index, 1)
    const text = item.label.replace('替换为：', '')
    quillInstance.insertText(index, text, { color: 'red' })
    quillInstance.setSelection(index + text.length)
  }
  showModal.value = false
  currentButtonData = null
}

onMounted(() => {
  console.log('组件已挂载')
})
</script>

<style scoped>
/* 这里不需要额外样式 */
</style>